package com.shurdroides.sintesi;

import java.util.List;

import javax.persistence.EntityManager;

public class ObjetoHelper  implements Controller<Long,Objeto>{

	EntityManager em;
	
	public ObjetoHelper(EntityManager em){
		setEntityManager(em);
	}
	
	@Override
	public void makePersistent(Objeto object) {

		try{
			em.getTransaction().begin();
			em.persist(object);
			em.getTransaction().commit();
		}catch(Exception e){
			em.getTransaction().rollback();
			e.printStackTrace();
		}finally{

		}
		
	}

	@Override
	public void update(Objeto object) {

		try{
			em.getTransaction().begin();
			em.merge(object);
			em.getTransaction().commit();
		}catch(Exception e){
			em.getTransaction().rollback();
			e.printStackTrace();
		}finally{

		}
		
	}

	@Override
	public void remove(Objeto object) {
		try{
			em.getTransaction().begin();
			em.remove(object);
			em.getTransaction().commit();
		}catch(Exception e){
			em.getTransaction().rollback();
			e.printStackTrace();
		}finally{

		}
		
	}

	@Override
	public Objeto getById(Long clau) {
		Objeto u = (Objeto) em.createQuery("select o from Objeto o where o.id_objeto=\""+clau+"\"").getSingleResult();
		return u;
	}

	@Override
	public Objeto getByName(String name) {
		Objeto u = (Objeto) em.createQuery("select o from Objeto o where o.nombre=\""+name+"\"").getSingleResult();
		return u;
	}

	@Override
	public int getCount() {
		List o = em.createQuery("select o from Objeto o").getResultList();
		return o.size();
	}

	@Override
	public void removeAll() {
		int o = em.createQuery("delete from Objeto o").executeUpdate();
		
	}

	@Override
	public List<Objeto> getList() {
		List o = em.createQuery("select o from Objeto o").getResultList();
		return o;
	}

	@Override
	public boolean containsKey(Long clau) {
		Objeto u = (Objeto) em.createQuery("select o from Objeto o where o.id_objeto=\""+clau+"\"").getSingleResult();
		return u!=null;
	}
	
	@Override
	public void setEntityManager(EntityManager em) {
		this.em=em;
		
	}


}
